package com.hl.card.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hl.card.common.persistence.model.DistinguishIdCard;
import com.hl.card.common.persistence.model.Recharge;
import com.hl.card.common.remote.user.RemoteUser;
import com.hl.card.common.remote.user.RemoteUserService;
import com.hl.card.common.util.ResponseObject;
import com.hl.card.modular.system.service.ISysDicService;
import com.hl.card.pay.dto.ChangeDto;
import com.hl.card.pay.service.ChangeService;
import com.hl.card.pay.util.PayDigestUtil;
import com.hl.card.pay.vo.ChangeVo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ChangeServiceImpl implements ChangeService {

    private Logger logger= LoggerFactory.getLogger(ChangeServiceImpl.class);

    @Value("${pay.config.baseUrl}")
    private String baseUrl;

    @Value("${pay.config.createOrder}")
    private String createOrder;

    @Value("${pay.config.trans}")
    private String trans;

    @Value("${pay.config.trade}")
    private String trade;

    @Value("${pay.config.mchInfo}")
    private String mchInfo;

    @Value("${pay.config.payChanel}")
    private String payChanel;

    @Value("${pay.config.reqKey}")
    private String reqKey;

    @Value("${pay.config.mchId}")
    private String mchId;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ISysDicService sysDicService;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private MongoTemplate mongoTemplate;

    private static String COLLECTION_NAME = "IdCardInfo";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String doChange(ChangeVo vo) {
        RemoteUser remoteUser=new RemoteUser();
        JSONObject json = remoteUserService.findSsoUserByUserId(vo.getUserId());
        if (json.get("code").equals("0")) {
            JSONObject userObj= (JSONObject) json.get("user");
            if(userObj != null) {
                remoteUser = JSON.parseObject(userObj.toJSONString(), RemoteUser.class);
            }
        }
        Map<String, Object> item = sysDicService.selectListByCodeNo("BDDHPZ", "EXCHRATE");
        String value = (String) item.get("dicValue");
        Map<String, Object> item2 =  sysDicService.selectListByCodeNo("BDDHMZ", vo.getCode());
        String amount= (String) item2.get("dicValue");
        int intAmount=Integer.parseInt(amount);
        int rate=Integer.parseInt(value);
        String param1= intAmount*rate+"";

        //绑定手机号
        String orderNo=System.currentTimeMillis()+"";
        Recharge recharge=new Recharge();
        recharge.setRecharge_no(orderNo);
        recharge.setExtra("EXCHANGE");
        recharge.setUser_id(vo.getUserId());
        recharge.setStatus(1);
        recharge.setAdd_time(new Date());
        recharge.setRecharge_no(orderNo);
        recharge.setAmount(Double.parseDouble(amount));
        recharge.setConsume(Double.parseDouble(param1));
        recharge.setBinding_phone(remoteUser.getMobilePhone());
        logger.info("兑换"+recharge.toString());
        recharge.insert();

        ChangeDto changeDto=new ChangeDto();
        BeanUtils.copyProperties(vo,changeDto);
        changeDto.setChannelUser(vo.getUserId());
        changeDto.setMchId(mchId);
        changeDto.setAction("EXCHANGE");
        changeDto.setMchTransNo(orderNo);
        changeDto.setRemarkInfo("比豆奖励转账");
        changeDto.setAmount(amount);
        changeDto.setParam1(param1);
        changeDto.setSubject("DH");
        changeDto.setBody("比豆兑换HTL");
        changeDto.setClientIp("211.94.116.218");
        changeDto.setCurrency("htl");
        JSONObject paramMap= (JSONObject) JSON.toJSON(changeDto);
        String reqSign = PayDigestUtil.getSign(paramMap, reqKey);//请求参数签名
        logger.info("获取签名："+reqSign);
        String url = baseUrl+trade;
        logger.info(url);
        JSONObject postData =(JSONObject) JSON.toJSON(changeDto);
        postData.put("sign",reqSign);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
        System.out.println(postData.toJSONString());
        map.add("params",postData.toJSONString());
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        String str = restTemplate.postForEntity(url, request, String.class).getBody();
        System.out.println(str);
        return str;
    }

    @Override
    public boolean checkExchange(String userId, String amount) {
        Query query = Query.query(Criteria.where("user_id").is(userId));
        DistinguishIdCard card = mongoTemplate.findOne(query,
                DistinguishIdCard.class, COLLECTION_NAME);
        if (card == null || "0".equals(card.getAuth())) {
            return false;
        } else {
            if ("1".equals(card.getAuth())) {
                return true;
            }
        }
        String day_limit = getDicValue("BDDHPZ", "PER_DAY_MAX");
        String mouth_limit = getDicValue("BDDHPZ", "PER_MOUTH_MAX");
        //String day_amount = stringRedisTemplate.opsForValue().set(userId + "PER_DAY_AMOUNT", "0", index + 24*60*60, TimeUnit.SECONDS);//设置连续签到过期时间
        String day_amount = stringRedisTemplate.opsForValue().get(userId + "PER_DAY_AMOUNT");
        String mouth_amount = stringRedisTemplate.opsForValue().get(userId + "PER_MOUTH__AMOUNT");

        Long amount_long = Long.parseLong(amount);

        Long day_amount_limit = Long.parseLong(day_limit) + amount_long;
        Long mouth_amount_limit = Long.parseLong(mouth_limit) + amount_long;

        Long day_amount_long = Long.parseLong(day_amount) + amount_long;
        Long mouth_amount_long = Long.parseLong(mouth_amount) + amount_long;
        if(day_amount_long <= day_amount_limit && mouth_amount_long <= mouth_amount_limit) {
            return true;
        }
        return false;
    }

    @Override
    public void setExchangeAmountRedis(String userId, String amount) {
        String day_amount = stringRedisTemplate.opsForValue().get(userId + "PER_DAY_AMOUNT");
        String mouth_amount = stringRedisTemplate.opsForValue().get(userId + "PER_MOUTH__AMOUNT");

        Long amount_long = Long.parseLong(amount);
        Long day_amount_long = Long.parseLong(day_amount) + amount_long;
        Long mouth_amount_long = Long.parseLong(mouth_amount) + amount_long;

        Date nextDay;
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        calendar.add(calendar.DATE,1);//把日期往前减少一天，若想把日期向后推一天则将负数改为正数
        nextDay = calendar.getTime();
//			calendar.add(calendar.DATE,1);//把日期往前减少一天，若想把日期向后推一天则将负数改为正数
//			thirdDay = calendar.getTime();
//			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

//			String dateString = formatter.format(nextDay);
//			System.out.println("当天签到状态过期时间 = " + dateString);
//			dateString = formatter.format(thirdDay);
//			System.out.println("连续签到过期时间 = " + dateString);

        long start = System.currentTimeMillis();
        long end = nextDay.getTime();
        int index = (int)((end - start) / 1000);
        System.out.println("过期秒数 = " + index);
        stringRedisTemplate.opsForValue().set(userId + "PER_MOUTH__AMOUNT", Long.toString(mouth_amount_long), index + 24*60*60, TimeUnit.SECONDS);//设置当月过期时间
        stringRedisTemplate.opsForValue().set(userId + "PER_DAY_AMOUNT", Long.toString(day_amount_long), index, TimeUnit.SECONDS);//设置当天兑换总数过期时间
    }

    private String getDicValue(String Code, String No) {
        ResponseObject res = new ResponseObject();
        res.setErroCode(1);
        res.setData("信息不存在");
        Map map=new HashMap<>();
        String value = null;
//        String version = stringRedisTemplate.opsForValue().get("VERSION" + ":" + plantform);
//        if(StringUtils.isNotBlank(version)) {
//            res.setErroCode(0);
//            map.put("version", version);
//            map.put("msg", "版本获取成功");
//            res.setData(map);
//        }else {
        Map<String, Object> item = sysDicService.selectListByCodeNo(Code, No);
        if(item != null) {
            value = (String) item.get("dicValue");
       }
        return value;
    }

}
